/**
 * Copyright (C) 2008-2009 Cristian Olaru <colaru@gmail.com>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *         http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.integrationpath.mengine.webapp.action;

import com.integrationpath.mengine.model.Article;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.compass.core.Compass;
import org.compass.core.CompassException;
import org.compass.core.CompassHits;
import org.compass.core.CompassSession;
import org.compass.core.CompassTransaction;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SearchAction extends ArticleAction {

	private static final long serialVersionUID = 1L;
	private List<Article> articles  = new ArrayList<Article>();
	private String clientQuery;

    public List<Article> getArticles() {
		return articles;
	}

	public String getClientQuery() {
		return clientQuery;
	}

	public void setClientQuery(String clientQuery) {
		this.clientQuery = clientQuery;
	}

	public String searchArticles() throws IOException {

    	Compass compass = (Compass) getSpringContext().getBean("compass");
    	String clientQuery = getRequest().getParameter("clientQuery");
    	CompassSession session = compass.openSession();
    	String query = "+content:" + clientQuery;
    	CompassTransaction tx = null;
    	try {
    	    tx = session.beginTransaction();

    	    CompassHits hits = session.queryBuilder().queryString(query)
    		    .toQuery()
//    		    .addSort("country",CompassQuery.SortPropertyType.STRING)
    		    .hits();

    	    prepareResponse(hits);

    	    tx.commit();
    	} catch (CompassException ce) {
    	    if (tx != null)
    		tx.rollback();
    	} finally {
    	    session.close();
    	}

    	return SUCCESS;
        } 
 
    private void prepareResponse(CompassHits hits) {
    	for (int i = 0; i < hits.length(); i++) {	
    		Article article = (Article)hits.data(i);
    		articles.add(article);
     	}
        }
    
    WebApplicationContext getSpringContext() {
    	return WebApplicationContextUtils.getWebApplicationContext(getRequest()
    		.getSession().getServletContext());
        }
}